<template>
  <div class="app-container">
    <el-card>
      <div class="header">
        <h2>{{ summary.examTitle }}</h2>
        <div class="meta">
          <span>结束时间: {{ summary.endTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          <span>总分: {{ summary.totalScore }}</span>
          <span>及格分: {{ summary.passScore }}</span>
        </div>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="统计概览" name="summary">
          <div class="stat-container">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">参与人数</div>
                  <div class="stat-value">{{ summary.participantCount }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">平均分</div>
                  <div class="stat-value">{{ summary.avgScore }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">通过率</div>
                  <div class="stat-value">{{ summary.passRate }}%</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-title">最高分/最低分</div>
                  <div class="stat-value">{{ summary.highestScore }}/{{ summary.lowestScore }}</div>
                </div>
              </el-col>
            </el-row>

            <div class="chart-container">
              <h3>分数段分布</h3>
              <div style="height: 300px;">
                <el-table :data="scoreDistributionData" style="width: 100%">
                  <el-table-column prop="range" label="分数段" width="180" />
                  <el-table-column prop="count" label="人数">
                    <template slot-scope="{row}">
                      <el-progress
                        :percentage="(row.count / summary.participantCount) * 100"
                        :show-text="false"
                      />
                      <span style="margin-left: 10px">{{ row.count }}人</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="题目统计" name="question">
          <el-table :data="questionStats" style="width: 100%">
            <el-table-column prop="sort" label="题号" width="80" />
            <el-table-column prop="title" label="题目" min-width="200" />
            <el-table-column prop="typeName" label="题型" width="120" />
            <el-table-column prop="score" label="分值" width="80" />
            <el-table-column prop="avgScore" label="平均得分" width="120">
              <template slot-scope="{row}">
                {{ row.avgScore }}/{{ row.score }}
              </template>
            </el-table-column>
            <el-table-column prop="correctRate" label="正确率" width="120">
              <template slot-scope="{row}">
                <el-progress :percentage="row.correctRate" />
              </template>
            </el-table-column>
            <el-table-column label="得分分布" min-width="300">
              <template slot-scope="{row}">
                <div style="display: flex; height: 30px; align-items: center;">
                  <div
                    v-for="(item, key) in row.scoreDistribution"
                    :key="key"
                    :style="{
                      width: `${(item / summary.participantCount) * 100}%`,
                      backgroundColor: getDistributionColor(key),
                      height: '20px',
                      marginRight: '2px'
                    }"
                    :title="`${key}: ${item}人`"
                  ></div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="考生成绩" name="student">
          <div class="filter-container">
            <el-input
              v-model="studentQuery.searchKey"
              placeholder="搜索学生姓名/学号"
              style="width: 200px"
              clearable
              @keyup.enter.native="handleStudentFilter"
            />

            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="handleStudentFilter"
            >
              搜索
            </el-button>
          </div>

          <el-table
            :data="studentScores"
            style="width: 100%; margin-top: 20px"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="userName" label="学号" width="300" sortable="custom" />
            <el-table-column prop="nickName" label="姓名" width="300" sortable="custom" />
            <el-table-column prop="score" label="成绩" width="300" sortable="custom">
              <template slot-scope="{row}">
                <span :class="{'pass': isPass(row.score), 'fail': !isPass(row.score)}">
                  {{ row.score }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="submitTime" label="提交时间" width="300" sortable="custom">
              <template slot-scope="{row}">
                {{ row.submitTime | parseTime('{y}-{m}-{d} {h}:{i}') }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="{row}">
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleStudentDetail(row.recordId)"
                >
                  详情
                </el-button>
                <el-button
                  type="warning"
                  size="mini"
                  @click="handleManualCorrect(row.recordId)"
                >
                  批改
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="studentTotal>0"
            :total="studentTotal"
            :page.sync="studentQuery.page"
            :limit.sync="studentQuery.limit"
            @pagination="getStudentScores"
          />
        </el-tab-pane>

        <el-tab-pane label="人工批改" name="manual">
          <el-tabs v-model="manualTab" type="card">
            <el-tab-pane label="按题目批改" name="byQuestion">
              <el-table :data="manualQuestions" style="width: 100%">
                <el-table-column prop="title" label="题目" min-width="200" />
                <el-table-column prop="typeName" label="题型" width="120" />
                <el-table-column prop="uncorrectedCount" label="待批改数量" width="120">
                  <template slot-scope="{row}">
                    <el-tag type="danger">{{ row.uncorrectedCount }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template slot-scope="{row}">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleCorrectQuestion(row.questionId)"
                    >
                      批改
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="按学生批改" name="byStudent">
              <el-table :data="manualStudents" style="width: 100%">
                <el-table-column prop="userName" label="学号" width="120" />
                <el-table-column prop="nickName" label="姓名" width="120" />
                <el-table-column prop="uncorrectedCount" label="待批改数量" width="120">
                  <template slot-scope="{row}">
                    <el-tag type="danger">{{ row.uncorrectedCount }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template slot-scope="{row}">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleCorrectStudent(row.recordId)"
                    >
                      批改
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>

        <el-tab-pane label="申诉处理" name="appeal">
          <el-table :data="appeals" style="width: 100%">
            <el-table-column prop="studentName" label="学生" width="120" />
            <el-table-column prop="appealContent" label="申诉内容" min-width="200" />
            <el-table-column prop="appealTime" label="申诉时间" width="300">
              <template slot-scope="{row}">
                {{ row.appealTime | parseTime('{y}-{m}-{d} {h}:{i}') }}
              </template>
            </el-table-column>
            <el-table-column prop="appealStatus" label="状态" width="120">
              <template slot-scope="{row}">
                <el-tag :type="row.appealStatus | statusFilter">
                  {{ row.appealStatus | statusNameFilter }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="{row}">
                <el-button
                  v-if="row.appealStatus !== 2"
                  type="primary"
                  size="mini"
                  @click="handleAppeal(row)"
                >
                  处理
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="handleViewAppealDetail(row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 学生考试详情对话框 -->
    <el-dialog
      :title="`${currentStudent.nickName} (${currentStudent.userName}) 的考试详情`"
      :visible.sync="studentDetailVisible"
      width="80%"
      top="5vh"
    >
      <student-exam-detail :record-id="currentRecordId" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="studentDetailVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 人工批改对话框 -->
    <el-dialog
      :title="manualCorrectTitle"
      :visible.sync="manualCorrectVisible"
      width="95%"
      top="5vh"
    >
      <manual-correct
        v-if="manualCorrectVisible"
        :record-id="currentRecordId"
        :question-id="currentQuestionId"
        @success="handleManualCorrectSuccess"
      />
    </el-dialog>

    <!-- 申诉处理对话框 -->
    <el-dialog
      :title="`处理申诉 - ${currentAppeal.studentName}`"
      :visible.sync="appealHandleVisible"
      width="50%"
    >
      <appeal-handle
        v-if="appealHandleVisible"
        :appeal="currentAppeal"
        @success="handleAppealSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getExamSummary,
  getQuestionStats,
  getTeacherScores,
  getManualCorrectQuestions,
  getManualCorrectStudents,
  getAppealList
} from '@/api/exam/score'
import StudentExamDetail from './StudentExamDetail'
import ManualCorrect from './ManualCorrect'
import AppealHandle from './AppealHandle'
import Pagination from '@/components/Pagination/index.vue'

export default {
  name: 'ScoreDetail',
  components: { StudentExamDetail, ManualCorrect, AppealHandle, Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'warning',
        1: 'danger',
        2: 'success'
      }
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusNameMap = {
        0: '未处理',
        1: '处理中',
        2: '已处理'
      }
      return statusNameMap[status]
    }
  },
  data() {
    return {
      examId: undefined,
      groupId: undefined,
      activeTab: 'summary',
      manualTab: 'byQuestion',

      // 统计概览数据
      summary: {
        examTitle: '',
        endTime: '',
        totalScore: 0,
        passScore: 0,
        participantCount: 0,
        avgScore: 0,
        passRate: 0,
        highestScore: 0,
        lowestScore: 0,
        scoreDistribution: {}
      },

      // 题目统计数据
      questionStats: [],

      // 考生成绩数据
      studentQuery: {
        page: 1,
        limit: 20,
        searchKey: undefined,
        sort: undefined,
        order: undefined
      },
      studentScores: [],
      studentTotal: 0,

      // 人工批改数据
      manualQuestions: [],
      manualStudents: [],

      // 申诉数据
      appeals: [],

      // 对话框控制
      studentDetailVisible: false,
      currentRecordId: undefined,
      currentStudent: {
        userName: '',
        nickName: ''
      },

      manualCorrectVisible: false,
      manualCorrectTitle: '',
      currentQuestionId: undefined,

      appealHandleVisible: false,
      currentAppeal: {}
    }
  },
  computed: {
    scoreDistributionData() {
      return Object.entries(this.summary.scoreDistribution).map(([range, count]) => ({
        range,
        count
      }))
    }
  },
  created() {
    this.examId = this.$route.query.examId
    this.groupId = this.$route.query.groupId
    this.getSummary()
    this.getQuestionStats()
    this.getStudentScores()
    this.getManualQuestions()
    this.getManualStudents()
    this.getAppeals()
  },
  methods: {
    getSummary() {
      getExamSummary(this.examId).then(response => {
        this.summary = response.data
      })
    },

    getQuestionStats() {
      getQuestionStats(this.examId).then(response => {
        this.questionStats = response.data
      })
    },

    getStudentScores() {
      getTeacherScores(this.examId,this.studentQuery).then(response => {
        this.studentScores = response.rows
        this.studentTotal = response.total
      })
    },

    getManualQuestions() {
      getManualCorrectQuestions(this.examId).then(response => {
        this.manualQuestions = response.data
      })
    },

    getManualStudents() {
      getManualCorrectStudents(this.examId).then(response => {
        this.manualStudents = response.data
      })
    },

    getAppeals() {
      getAppealList(this.examId).then(response => {
        this.appeals = response.data
      })
    },

    handleTabClick(tab) {
      if (tab.name === 'student' && this.studentScores.length === 0) {
        this.getStudentScores()
      } else if (tab.name === 'manual') {
        this.getManualQuestions()
        this.getManualStudents()
      } else if (tab.name === 'appeal') {
        this.getAppeals()
      }
    },

    handleStudentFilter() {
      this.studentQuery.page = 1
      this.getStudentScores()
    },

    handleSortChange({ column, prop, order }) {
      this.studentQuery.sort = prop
      this.studentQuery.order = order === 'ascending' ? 'asc' : 'desc'
      this.getStudentScores()
    },

    isPass(score) {
      return score >= this.summary.passScore
    },

    getDistributionColor(key) {
      const colorMap = {
        '满分': '#67C23A',
        '80%-99%': '#85CE61',
        '60%-79%': '#E6A23C',
        '40%-59%': '#F56C6C',
        '0%-39%': '#F78989',
        '0分': '#909399'
      }
      return colorMap[key] || '#909399'
    },

    handleStudentDetail(recordId) {
      this.currentRecordId = recordId
      const student = this.studentScores.find(s => s.recordId === recordId)
      if (student) {
        this.currentStudent = {
          userName: student.userName,
          nickName: student.nickName
        }
      }
      this.studentDetailVisible = true
    },

    handleManualCorrect(recordId) {
      this.currentRecordId = recordId
      const student = this.studentScores.find(s => s.recordId === recordId)
      this.manualCorrectTitle = `批改 ${student.nickName} (${student.userName}) 的试卷`
      this.manualCorrectVisible = true
    },

    handleCorrectQuestion(questionId) {
      this.currentQuestionId = questionId
      const question = this.manualQuestions.find(q => q.questionId === questionId)
      this.manualCorrectTitle = `批改题目: ${question.title}`
      this.manualCorrectVisible = true
    },

    handleCorrectStudent(recordId) {
      this.currentRecordId = recordId
      const student = this.manualStudents.find(s => s.recordId === recordId)
      this.manualCorrectTitle = `批改 ${student.nickName} (${student.userName}) 的试卷`
      this.manualCorrectVisible = true
    },

    handleManualCorrectSuccess() {
      this.manualCorrectVisible = false
      this.getStudentScores()
      this.getManualQuestions()
      this.getManualStudents()
    },

    handleAppeal(appeal) {
      this.currentAppeal = appeal
      this.appealHandleVisible = true
    },

    handleViewAppealDetail(appeal) {
      this.currentAppeal = appeal
      // 这里可以打开一个详情对话框或跳转到详情页面
      this.$message.info('查看申诉详情: ' + appeal.appealContent)
    },

    handleAppealSuccess() {
      this.appealHandleVisible = false
      this.getAppeals()
    }
  }
}
</script>

<style scoped>
.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.header h2 {
  margin: 0 0 10px 0;
}

.meta span {
  margin-right: 20px;
  color: #666;
}

.stat-container {
  margin-top: 20px;
}

.stat-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.chart-container {
  margin-top: 30px;
}

.chart-container h3 {
  margin-bottom: 15px;
}

.pass {
  color: #67C23A;
  font-weight: bold;
}

.fail {
  color: #F56C6C;
  font-weight: bold;
}
</style>
